// This is the main DLL file.

#include "stdafx.h"

#include "Util.h"
using namespace System::IO;
using namespace System::Runtime::InteropServices; // for class Marshal
using namespace System::Diagnostics;

namespace ManagedAPI
{
	char* Util::StringToChar( String^ str)
	{
		/* MSDN: StringToHGlobalAnsi is useful for custom marshaling or when mixing managed and unmanaged code. 
		* Since this method allocates the unmanaged memory required for a string, always free the memory 
		* by calling FreeHGlobal. */
		char* result = (char*)(void*)Marshal::StringToHGlobalAnsi(str);
		return result;
	}
	
	void Util::FreeNativeString(const char* nativeString)
	{
		char* charptr = const_cast<char*>( nativeString );
		IntPtr ptr = static_cast<IntPtr>( charptr );
		Marshal::FreeHGlobal(ptr);
	}

	array<Entity^>^ Util::ReferenceToEntityArray( array<Reference^>^ parray)
	{
		array<Entity^>^ result = nullptr;
		if (parray != nullptr)
		{
			int count = parray->Length;
			result = gcnew array<Entity^>(count);
			for (int i = 0; i < count ; i++)
			{
				result[i] = parray[i]->ThisEntity;
			}
		}
		return result;
	}

	String^ Util::CleanUpType(String^ type)
	{
		// get rid of pointer symbols
		String^ temp = type->Replace("*", "");
		// get rid of address symbols
		temp = temp->Replace("&", "");
		// define splitter characters
		array<wchar_t>^ splitter = {' ','\t'};
		// split up the string
		array<String^>^ splits = temp->Split(splitter, StringSplitOptions::RemoveEmptyEntries);
		// hopefully the type is the last one after we split a type. If not this method will not work.
		String^ lastOne = splits[splits->Length - 1];
		return lastOne->Trim();
	}
}